package de.fhbrs.migration;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

/**
 * With this function it is possible to set up a new MySQL 
 * Connection.
 * 
 * @version $Id: MySQLConnection.java 379 2008-01-17 15:27:36Z andreas.moser.bm $
 * @author 	Andreas Moser
 * 
 * 001 10.12.2007 - Andreas Moser - Added all Standard Comments
 * 
 */
public class MySQLConnection {
	private final static String DBDRIVER = "com.mysql.jdbc.Driver";
	private String connstr =  "jdbc:mysql://";
	private String hostname = "";
	private String database = "";
	private String username = "";
	private String password = "";
	
	private static MySQLConnection instance;
	
	private MySQLConnection(String hostname, String database, String username, String password) {
		if (this.hostname.length() == 0) 
			readFlatFile(hostname, database, username, password);
	}
	
	public synchronized static MySQLConnection getInstance(String hostname, String database, String username, String password)
	{
		if(instance == null)
		{
			instance = new MySQLConnection(hostname, database, username, password);
		}
		return instance;
	}
	
	/** 
     * Execute INSERT, DELETE, UPDATE, DROP, TRUNCATE query
     * @param query INSERT query as string
     */
	public int executeUpdate(String query) throws Exception, NoMySQLConException {
		Connection con = null;
		Class.forName(DBDRIVER).newInstance();
		con = DriverManager.getConnection(connstr,username,password);
		Statement statement = con.createStatement();
		int rows = statement.executeUpdate(query);
		statement.close();
		con.close();
		return rows;
	}
	
	/** 
     * Execute SELECT query
     * @param query SELECT query as string
     * @return ResultSet
     */
	public ResultSet executeQuery(String query) throws Exception, NoMySQLConException {
		Connection con = null;
		Class.forName(DBDRIVER).newInstance();
		con = DriverManager.getConnection(connstr,username,password);
		Statement statement = con.createStatement();
		ResultSet result = statement.executeQuery(query);
		con.close();
		return result;
	}
	
	/** 
     * Reads username and password for database access from a flat file
     */
	private void readFlatFile(String hostname, String database, String username, String password) {
		this.hostname = hostname;
		this.database = database;
		this.username = username;
		this.password = password;
		connstr += this.hostname + "/" + this.database;
	}
}